// import {
//   FILE_TYPE
// } from './constant';
import httphelper from "./HttpHelper.js";

export default {
  // 判断是手机还是pc
  isMobile() {
    let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    return flag;
  }, 
  // http://bjlm.bosihw.cn
  // http://test0430.bosihw.cn/
  // 微信支付
  async getWxpaydetail(WechatType, Type, Money, Cid) {
    if (this.isMobile()) {
      const res = await httphelper.post('/api/LmPayApi/WeChatPay',
        {
          Sign: "string",
          WechatType: WechatType,
          Type: Type,
          Money: Money,
          AuthorId: localStorage.getItem('AuthorId'),
          JournalID: 2020,
          PageUrl: "http://bjlm.bosihw.cn/payerror?type=" + Type,
          CID: Cid
        });
      return res;
    } else {
      const res_1 = await httphelper.post('/api/LmPayApi/WxPay',
        {
          Sign: "string",
          Type: Type,
          Money: Money,
          AuthorId: localStorage.getItem('AuthorId'),
          JournalID: 2020,
          PageUrl: "http://bjlm.bosihw.cn/paysuccess?type=" + Type,
          CID: Cid
        });
      return res_1;
    }
  },


  // 支付宝支付
  async zfbpaydetail(WechatType, Type, Money, Cid) {
    if (this.isMobile()) {
      const res = await httphelper.post('/api/LmPayApi/NewZFBPay',
        {
          Sign: "string",
          WechatType: WechatType,
          Type: Type,
          Money: Money,
          AuthorId: localStorage.getItem('AuthorId'),
          JournalID: 2020,
          PageUrl: "http://bjlm.bosihw.cn/payerror?type=" + Type,
          CID: Cid
        });
      return res;
    } else {
      const res_1 = await httphelper.post('/api/LmPayApi/ZFBPay',
        {
          Sign: "string",
          Type: Type,
          Money: Money,
          AuthorId: localStorage.getItem('AuthorId'),
          JournalID: 2020,
          PageUrl: "http://bjlm.bosihw.cn/paysuccess?type=" + Type,
          CID: Cid
        });
      return res_1;
    }
  },



  /**
   * 判断是否为空
   * @param val
   * @returns {boolean}
   */
  isEmpty(val) {
    if (typeof val === 'undefined') {
      return true;
    } else if (val === null) {
      return true;
    } else if (typeof val === 'string' && val === '') {
      return true;
    } else if (typeof val === 'number' && isNaN(val)) {
      return true;
    } else if (Array.isArray(val) && val.length === 0) {
      return true;
    } else if (val instanceof Number && isNaN(val)) {
      return true;
    } else if (val.toString() === '[object Object]' && Object.keys(val).length === 0) {
      return true;
    } else {
      return false;
    }
  },

  /**
   * 判断是否为不为空
   * @param val
   * @returns {boolean}
   */
  isNotEmpty(val) {
    return !this.isEmpty(val);
  },

  /**
   * 判断数组元素是否都相等（基本数据类型）
   * @param val
   * @returns {boolean}
   */
  isEqualAll(val) {
    if (this.isNotEmpty(val)) {
      return !val.some(e => {
        return e !== val[0];
      });
    } else {
      return true;
    }
  },

  /**
   * 字符串去空格
   * @param val
   * @returns {*}
   */
  trim(val) {
    if (this.isNotEmpty(val)) {
      return val.replace(/[\s\uFEFF\xa0\u3000]/g, '');
    } else {
      return val;
    }
  },

  /**
   * 浮点数比较
   * @param val
   * @param other
   * @returns {boolean}
   */
  floatEqual: (function () {
    const SAFE_VALUE = 0.0000000001;
    return (val = 0, other = 0) => {
      val = Number(val);
      other = Number(other);
      if (isNaN(val) || isNaN(other)) {
        return false;
      } else {
        return val === other ? true : Math.abs(val - other) < SAFE_VALUE ? true : false;
      }
    };
  })(),

  /**
   * 复制属性方法
   * @param target
   * @param source
   * @returns {{}}
   */
  copyProperties(target, source) {
    if (!target || !source) {
      return target;
    }
    Object.keys(target).forEach(e => {
      target[e] = e in source ? source[e] : target[e];
    });
    return target;
  },

  /**
   * 替换元素Class
   * @param element
   * @param oldStr
   * @param newStr
   */
  replaceClassName(element, oldStr, newStr) {
    element.className = element.className.replace(oldStr, newStr);
  },

  /**
   * 添加事件绑定
   * @param element
   * @param event
   * @param handler
   */
  addEvent: (function () {
    if (document.addEventListener) {
      return (element, event, handler) => {
        element.addEventListener(event, handler, false);
      }
    } else if (document.attachEvent) {
      return (element, event, handler) => {
        element.attachEvent('on' + event, handler);
      }
    } else {
      return (element, event, handler) => {
        element['on' + event] = handler;
      }
    }
  })(),

  /**
   * 移除事件绑定
   * @param element
   * @param event
   * @param handler
   */
  removeEvent: (function () {
    if (document.removeEventListener) {
      return (element, event, handler) => {
        element.removeEventListener(event, handler, false);
      }
    } else if (document.detachEvent) {
      return (element, event, handler) => {
        element.detachEvent('on' + event, handler);
      }
    } else {
      return (element, event, handler) => {
        element['on' + event] = null;
      }
    }
  })(),

  /**
   * 获取Event
   * @param {*} event
   */
  getEvent(event) {
    return event ? event : window.event;
  },

  /**
   * 获取事件来源
   * @param {*} event
   */
  getTarget(event) {
    return event.target || event.srcElement;
  },

  /**
   * 阻止默认行为
   * @param {*} event
   */
  preventDefault(event) {
    if (event.preventDefault) {
      event.preventDefault();
    } else {
      event.returnValue = false;
    }
  },

  /**
   * 阻止事件传播
   * @param {*} event
   */
  stopPropagation(event) {
    if (event.stopPropagation) {
      event.stopPropagation();
    } else {
      event.cancelBubble = true;
    }
  },

  /**
   * 下载文件
   * @param url, @param fileName
  */
  download(url, fileName = '') {
    // console.log(11)
    let isChrome = this.getBrowser().versions.chrome;
    if (isChrome) {
      let a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      a.click();
    } else {
      // window.open(url);
    }
  },

  /**
   * 打开新窗口
   * @param {*} url
   * @param {*} title
   * @param {*} w
   * @param {*} h
   */
  openWindow(url, title, w, h) {
    // Fixes dual-screen position                            Most browsers       Firefox
    let dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
    let dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;

    let width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
    let height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

    let left = ((width / 2) - (w / 2)) + dualScreenLeft;
    let top = ((height / 2) - (h / 2)) + dualScreenTop;
    let newWindow = window.open(url, title, 'titlebar=yes, toolbar=yes, menubar=yes, scrollbars=yes, location=yes, directories=yes, status=yes, resizable=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

    // Puts focus on the newWindow
    if (window.focus) {
      newWindow.focus();
    }
  },

  /**
   * 获取一个随机数
   * @param min 最小值
   * @param max 最大值
   * @returns {number}
   */
  getRandomNum(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  },

  /**
   * 获取一个随机颜色
   * @param min 最小值
   * @param max 最大值
   * @returns {string}
   */
  getRandomColor(min, max) {
    let r = this.getRandomNum(min, max);
    let g = this.getRandomNum(min, max);
    let b = this.getRandomNum(min, max);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
  },

  /**
   * 获取HashCode
   * @param {*} val
   */
  getHashCode(val) {
    let hash = 0;
    if (this.isEmpty(val)) {
      return hash;
    }
    if (typeof val === 'object') {
      val = JSON.stringify(val);
    }
    for (let i = 0, len = val.length; i < len; i++) {
      let char = val.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return hash;
  },

  /**
   * 获取浏览器信息
   * @returns {{versions: {trident, presto, webKit, gecko, mobile, ios, android, iPhone, iPad, webApp, weixin, alipay, qq}, language: string}}
   */
  getBrowser() {
    return {
      navigator: navigator,
      appVersion: navigator.appVersion,
      userAgent: navigator.userAgent,
      language: (navigator.browserLanguage || navigator.language).toLowerCase(),
      versions: (function () {
        let u = navigator.userAgent;
        return {
          trident: u.includes('Trident'), //IE内核
          presto: u.includes('Presto'), //opera内核
          webKit: u.includes('AppleWebKit'), //苹果、谷歌内核
          gecko: u.includes('Gecko') && !u.includes('KHTML'), //火狐内核
          ie: window.ActiveXObject || 'ActiveXObject' in window, //是否为IE
          edge: u.includes('Edge'), //是否为Edge
          opera: u.includes('Opera'), //是否为Opera
          firefox: u.includes('Firefox'), //是否为Firefox
          safari: u.includes('Safari') && !u.includes('Chrome'), //是否为Safari
          chrome: u.includes('Chrome') && u.includes('Safari') && !u.includes('Edge'), //是否为Chrome
          win: u.includes('Win'), //是否为Windows
          mac: u.includes('Mac'), //是否为Mac
          mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
          ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //是否为ios终端
          android: u.includes('Android') || u.includes('Adr'), //是否为android终端
          iPhone: u.includes('iPhone'), //是否为iPhone或者QQHD浏览器
          iPad: u.includes('iPad'), //是否为iPad
          webApp: !u.includes('Safari'), //是否为web应用程序，没有头部与底部
          weChat: u.includes('MicroMessenger'), //是否为微信
          alipay: u.includes('AlipayClient'), //是否为支付宝
          weibo: u.includes('Weibo'), //是否为微博
          dingTalk: u.includes('DingTalk'), //是否为钉钉
          qq: u.match(/QQ\//i) === 'QQ/' //是否为QQ
        };
      })()
    };
  },

  /**
   * 获取日期时间信息
   * @param val
   */
  getDateInfo(val) {
    let date, year, month, week, day, hours, minutes, seconds, time;
    date = this.isNotEmpty(val) ? new Date(val) : new Date();
    year = date.getFullYear();
    month = date.getMonth() + 1;
    month = (month > 9) ? month : `0${month}`;
    week = date.getDay();
    day = date.getDate();
    day = (day > 9) ? day : `0${day}`;
    hours = date.getHours();
    hours = (hours > 9) ? hours : `0${hours}`;
    minutes = date.getMinutes();
    minutes = (minutes > 9) ? minutes : `0${minutes}`;
    seconds = date.getSeconds();
    seconds = (seconds > 9) ? seconds : `0${seconds}`;
    time = date.getTime();
    return (function () {
      return {
        date: date,
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        week: week,
        day: date.getDate(),
        hours: date.getHours(),
        minutes: date.getMinutes(),
        seconds: date.getSeconds(),
        dateInfo: `${year}-${month}-${day}`,
        timeInfo: `${hours}:${minutes}:${seconds}`,
        dateTimeInfo: `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
        time: time
      };
    })();
  },

  /**
   * 获取应用路径
   * @returns
   */
  getBasePath() {
    return window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
  },

  /**
   * 获取文件类型
   */
  // getFileType(fileName) {
  //   let suffix = fileName.substring(fileName.lastIndexOf('.') + 1).toLocaleLowerCase();
  //   switch (suffix) {
  //     case 'jpg':
  //     case 'jpeg':
  //     case 'png':
  //     case 'gif':
  //       return FILE_TYPE.IMAGE;
  //     case 'txt':
  //       return FILE_TYPE.TXT;
  //     case 'pdf':
  //       return FILE_TYPE.PDF;
  //     case 'doc':
  //     case 'docx':
  //       return FILE_TYPE.WORD;
  //     case 'xls':
  //     case 'xlsx':
  //       return FILE_TYPE.EXCEL;
  //     case 'ppt':
  //     case 'pptx':
  //       return FILE_TYPE.PPT;
  //     case 'zip':
  //       return FILE_TYPE.ZIP;
  //     case 'rar':
  //       return FILE_TYPE.RAR;
  //     default:
  //       return FILE_TYPE.OTHER;
  //   }
  // },

  /**
   * 根据编码规则，计算每一级的长度
   * 输入的是:'3-2-2-2-2-2-2',返回的是一个函数
   */
  levelFn(levels) {
    let l = levels;
    let r = [];
    let i = 0;
    if (_.isNull(levels)) {
      return (code) => {
        return 0;
      };
    }
    r.push(parseInt(l.substr(0, 1)));
    let idx = l.indexOf('-');
    while (idx >= 0) {
      r.push(r[i] + parseInt(l.substr(idx + 1, 1)));
      i++;
      l = l.substring(idx + 2);
      idx = l.indexOf('-');
    }
    return (code) => {
      return r.indexOf(code.length) + 1;
    };
  },

  /**
   * 判断一个集合（数组）是否包含另一个集合（数组）的所有元素
   */
  includeAll(allArray, subArray) {
    return _.every(subArray, item => {
      return allArray.includes(item);
    });
  },



  // 修改日期格式
  formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + '';
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
      }
    }
    return fmt;
  },

  padLeftZero(str) {
    return ('00' + str).substr(str.length);
  }

};
